#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'wshu'
__version__ = '1.0'
"""
    ***********************************
    *  @filename : Host.py
    *  @Author : wshu
    *  @CodeDate : 2020/4/16 21:30
    *  @Software : PyCharm
    ***********************************
"""
import sys
import pprint
from . import Service
import xml.dom.minidom


class Host:

    def __init__(self, HostNode):
        self.host_node = HostNode
        self.status = HostNode.getElementsByTagName('status')[0].getAttribute('state')
        self.ip = HostNode.getElementsByTagName('address')[0].getAttribute('addr')

    def get_ports(self, protocol, state):
        '''get a list of ports which is in the special state'''

        open_ports = []

        for port_node in self.host_node.getElementsByTagName('port'):
            if port_node.getAttribute('protocol') == protocol and port_node.getElementsByTagName('state')[
                0].getAttribute('state') == state:
                open_ports.append(port_node.getAttribute('portid'))

        return open_ports

    def get_service(self, protocol, port):
        '''return a Service object'''

        for port_node in self.host_node.getElementsByTagName('port'):
            if port_node.getAttribute('protocol') == protocol and port_node.getAttribute('portid') == port:
                # bug fix for nmap 5.21
                # print '>> debug:',port_node.getElementsByTagName('service'),protocol,port,port_node.toxml()
                # port_node.getElementsByTagName('service') maybe cann't find service tag
                # by cosine 2020-04-16
                #
                if not port_node.getElementsByTagName('service'):
                    continue
                service_node = port_node.getElementsByTagName('service')[0]
                service = Service.Service(service_node)

                return service
        return None


if __name__ == '__main__':

    dom = xml.dom.minidom.parse('i.xml')
    host_nodes = dom.getElementsByTagName('host')

    if len(host_nodes) == 0:
        sys.exit()

    host_node = dom.getElementsByTagName('host')[0]

    h = Host(host_node)
    print('hahaha----', h)